#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>

#define SERVER_IP   "127.0.0.1"
#define SERVER_PORT 8387
#define CLIENT_PORT 8751
#define BUFF_LEN 512

void udp_msg_sender(int fd, struct sockaddr* dst, const char *pData)
{

    socklen_t len;
    struct sockaddr_in src;
    char buf[BUFF_LEN];
    struct timeval timeOut;
    
    /* 设置阻塞超时 */
    timeOut.tv_sec = 5;                 //设置5s超时
    timeOut.tv_usec = 0;
    setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &timeOut, sizeof(timeOut));

    len = sizeof(*dst);
    sendto(fd, pData, strlen(pData), 0, dst, len);
    
    while (1)
    {
        bzero(buf, BUFF_LEN);
        if (0 > recvfrom(fd, buf, BUFF_LEN, 0, (struct sockaddr*)&src, &len))  //接收来自server的信息
        {
            if (errno == EAGAIN)
            {
                break;
            }
        }

        if (0 == strcmp(buf, "byecli"))
        {
            break;
        }
        printf("%s", buf);
    }
}

/*
    client:
            socket-->sendto-->revcfrom-->close
*/

int main(int argc, char* argv[])
{
    int client_fd;
    struct sockaddr_in ser_addr;
    char buf[BUFF_LEN] = {0};

    client_fd = socket(AF_INET, SOCK_DGRAM, 0);
    if(client_fd < 0)
    {
        printf("create socket fail!\n");
        return -1;
    }

    for (int i=1; i<argc; i++)
    {
        strcat(buf, argv[i]);
        strcat(buf, " ");
    }

    //printf("cli:%s\n", buf);

    memset(&ser_addr, 0, sizeof(ser_addr));
    ser_addr.sin_family = AF_INET;
    ser_addr.sin_addr.s_addr = inet_addr(SERVER_IP);
    //ser_addr.sin_addr.s_addr = htonl(INADDR_ANY);  //注意网络序转换
    ser_addr.sin_port = htons(SERVER_PORT);  //注意网络序转换

    udp_msg_sender(client_fd, (struct sockaddr*)&ser_addr, buf);

    close(client_fd);

    return 0;
}
